<template>
  <div>
    <!-- 回到顶部 -->
    <el-backtop target=".app-main"></el-backtop>
    <!-- 展示列表 -->
    <div v-show="!isShowAddForm" class="show-list">
      <el-card style="margin-top: 10px" shadow="hover">
        <div style="display: flex; justify-content: space-between">
          <div>
            <div>
              <el-button
                size="mini"
                style="width: 100%"
                type="primary"
                icon="el-icon-plus"
                @click="isShowAddForm = true"
                >添加优惠券</el-button
              >
            </div>
            <div style="margin-top: 5px">
              <el-input
                style="width: 79%"
                size="mini"
                placeholder="搜索..."
                type=""
                v-model.trim="searchKeyword"
                @keyup.native.enter="searchCoupon"
              ></el-input
              ><el-button
                style="margin-left: 1px"
                type="success"
                size="mini"
                icon="el-icon-search"
                @click="searchCoupon"
              ></el-button>
            </div>
          </div>
          <div>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              title="删除选中"
              @click="delSelect"
            ></el-button>
          </div>
        </div>
      </el-card>
      <!-- 表格 -->
      <el-card style="margin-top: 10px">
        <el-table
          :data="couponList"
          :height="tableHeigth || undefined"
          border
          @selection-change="selectChange"
        >
          <el-table-column label="" align="center" width="" type="selection">
          </el-table-column>
          <el-table-column
            label="名称"
            :fixed="fixedCouponName"
            align=""
            width=""
            prop="couponName"
          >
            <template #header>
              <span>名称</span>
              <FixedTableHead
                :fixedHeader.sync="fixedCouponName"
                fixedText="取消固定该列"
                unFixedText="固定该列"
              ></FixedTableHead>
            </template>
          </el-table-column>
          <el-table-column label="描述" align="" width="" prop="rangeDesc">
          </el-table-column>
          <el-table-column
            label="类型"
            align=""
            width=""
            prop="couponTypeString"
            :filters="[
              { text: '现金券', value: 'SASH' },
              { text: '满减', value: 'FULL_REDUCTION' }
            ]"
            :filter-method="filterCouponType"
          >
          </el-table-column>
          <!-- <el-table-column
          label="优惠金额"
          align=""
          width=""
          prop="benefitAmount"
        >
        </el-table-column>
        <el-table-column
          label="优惠折扣"
          align=""
          width=""
          prop="benefitDiscount"
        >
        </el-table-column>
        <el-table-column
          label="条件金额"
          align=""
          width=""
          prop="conditionAmount"
        >
        </el-table-column>
        <el-table-column label="条件数量" align="" width="" prop="conditionNum">
        </el-table-column>
        <el-table-column label="开始时间" align="" width="" prop="startTime">
        </el-table-column>
        <el-table-column label="结束时间" align="" width="" prop="endTime">
        </el-table-column>
        <el-table-column label="限制数量" align="" width="" prop="limitNum">
        </el-table-column> -->
          <el-table-column label="操作" align="" width="" prop="">
            <template #default="{ row }">
              <el-button-group>
                <el-button
                  icon="el-icon-edit"
                  size="mini"
                  type="warning"
                  @click="eidtCouponInfo(row)"
                  >修改</el-button
                >
                <el-popconfirm
                  @onConfirm="delCouponInfo(row.id)"
                  title="确定删除吗？"
                >
                  <template #reference>
                    <el-button icon="el-icon-delete" size="mini" type="danger"
                      >删除</el-button
                    >
                  </template>
                </el-popconfirm>
              </el-button-group>
            </template>
          </el-table-column>
          <el-table-column type="expand" label="查看">
            <template #default="{ row }">
              <el-form class="demo-table-expand">
                <el-form-item label="名称">
                  <el-tag type="success"> {{ row.couponName }} </el-tag>
                </el-form-item>
                <el-form-item label="描述">
                  <span>{{ row.rangeDesc }}</span>
                </el-form-item>
                <el-form-item label="类型">
                  <el-tag type="info">{{ row.couponTypeString }} </el-tag>
                </el-form-item>
                <el-form-item label="优惠金额">
                  <span>{{ row.benefitAmount }}</span>
                </el-form-item>
                <el-form-item label="优惠折扣">
                  <span>{{ row.benefitDiscount }}</span>
                </el-form-item>
                <el-form-item label="条件金额">
                  <span>{{ row.conditionAmount }}</span>
                </el-form-item>
                <el-form-item label="条件数量">
                  <span>{{ row.conditionNum }}</span>
                </el-form-item>
                <el-form-item label="开始时间">
                  <el-tag effect="plain" type="success">{{
                    row.startTime
                  }}</el-tag>
                </el-form-item>
                <el-form-item label="结束时间">
                  <el-tag effect="plain" type="danger">{{
                    row.endTime
                  }}</el-tag>
                </el-form-item>
                <el-form-item label="限制数量">
                  <span>{{ row.limitNum }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column
            width="50"
            align="center"
            label="序号"
            :sortable="true"
            type="index"
          >
            <template #header>
              <FixedTableHead :fixedHeader.sync="fixedHeader"></FixedTableHead>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            class="phone"
            v-show="showPagination"
            @current-change="pageChange"
            style="text-align: center"
            :current-page="curPage"
            :page-size="pageLimt"
            :total="total"
            layout="slot,total, prev, next, jumper, ->"
          >
            <template>
              <div class="block">
                <el-slider
                  @change="pageLimtChange"
                  v-model="sliderValue"
                  :min="1"
                  :max="500"
                  show-input
                  input-size="mini"
                >
                </el-slider>
              </div>
            </template>
          </el-pagination>
          <el-pagination
            class="computer"
            v-show="showPagination"
            @current-change="pageChange"
            style="text-align: center"
            :current-page="curPage"
            :page-size="pageLimt"
            :total="total"
            layout="slot,total, prev,pager, next, jumper, ->"
          >
            <template>
              <div class="block">
                <el-slider
                  @change="pageLimtChange"
                  v-model="sliderValue"
                  :min="1"
                  :max="500"
                  show-input
                  input-size="mini"
                >
                </el-slider>
              </div>
            </template>
          </el-pagination>
        </div>
      </el-card>
    </div>

    <!-- 添加,修改优惠券 -->
    <div v-show="isShowAddForm" class="add-edit-coupon">
      <!-- 表单 -->
      <el-card
        :header="form.id ? '修改优惠券' : '添加优惠券'"
        class="addcoupon-card"
      >
        <template #header>
          <span style="font-weight: bold">{{
            form.id ? '修改优惠券' : '添加优惠券'
          }}</span>
        </template>
        <el-form
          label-position="right"
          label-width="10%"
          :rules="formRules"
          :model="form"
          ref="form"
        >
          <el-form-item label="名称" prop="couponName">
            <el-input class="width30" v-model.trim="form.couponName"></el-input>
          </el-form-item>
          <el-form-item label="描述">
            <el-input
              autosize
              type="textarea"
              class="width40"
              v-model.trim="form.rangeDesc"
            ></el-input>
          </el-form-item>
          <el-form-item label="类型" prop="couponType">
            <el-select v-model="CouponType" @change="selectCouponType">
              <el-option label="现金券" value="SASH|现金券"></el-option>
              <el-option label="满减" value="FULL_REDUCTION|满减"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="优惠">
            <div style="display: flex; gap: 10px">
              <div label="" style="display: inline">
                <span>优惠金额</span>
                <el-input type="number" v-model="form.benefitAmount"></el-input>
              </div>
              <div label="" style="display: inline">
                <span>优惠折扣</span>
                <el-input
                  type="number"
                  v-model="form.benefitDiscount"
                ></el-input>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="条件">
            <div style="display: flex; gap: 10px">
              <div label="" style="display: inline">
                <span>条件金额</span>
                <el-input
                  type="number"
                  v-model="form.conditionAmount"
                ></el-input>
              </div>
              <div label="" style="display: inline">
                <span>条件数量</span>
                <el-input type="number" v-model="form.conditionNum"></el-input>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="时间">
            <el-date-picker
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="selectStartAndEndTime"
              v-model="startAndEndTime"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item label="限制数量">
            <el-input
              type="number"
              class="width20"
              v-model="form.limitNum"
            ></el-input>
          </el-form-item>
          <el-form-item label="适用的SKU">
            <el-button @click="clickSelectSku">选择SKU</el-button>
            <el-collapse>
              <el-collapse-item title="已选择的SKU列表:" name="1">
                <el-table :data="selectSkuList">
                  <el-table-column
                    type="index"
                    label="序号"
                    align="center"
                    width="50"
                  ></el-table-column>
                  <el-table-column
                    type=""
                    label="ID"
                    align="center"
                    width=""
                    prop="id"
                  ></el-table-column>
                  <el-table-column
                    type=""
                    label="名称"
                    align=""
                    width=""
                    prop="skuName"
                  ></el-table-column>
                </el-table>
              </el-collapse-item>
            </el-collapse>
          </el-form-item>
          <el-form-item>
            <div style="display: flex; justify-content: right">
              <el-button type="primary" @click="addCouponInfo">保存</el-button>
              <el-button @click="isShowAddForm = false">取消</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-card>
      <!--选择SKU  -->
      <SelectSKU
        :visible.sync="isShowSelectSKU"
        @getSelectList="getSelectList"
      ></SelectSKU>
    </div>
  </div>
</template>

<script>
import SelectSKU from './SelectSKU'
export default {
  components: { SelectSKU },
  data() {
    return {
      //批量删除
      delCouponIdList: [],
      //添加优惠券
      isShowAddForm: false,
      selectSkuList: [],
      isShowSelectSKU: false,
      formRules: {
        couponName: [
          {
            required: true,
            message: '请输入名称'
          }
        ],
        couponType: [{ required: true, message: '请选择类型' }]
      },
      CouponType: '',
      form: this.getform(),
      //日期选择
      startAndEndTime: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      //固定名称
      fixedCouponName: false,
      //搜索
      showPagination: true,
      searchKeyword: '',
      //
      fixedHeader: false,
      total: 0,
      curPage: 1,
      pageLimt: 10,
      sliderValue: 10,
      couponList: []
    }
  },
  computed: {
    tableHeigth() {
      return this.fixedHeader ? '60vh' : ''
    }
  },
  watch: {
    $route: {
      immediate: true,
      handler(val) {
        const { page = undefined, limit = undefined } = val.query
        if (page) {
          this.curPage = parseInt(page)
        }
        if (limit) {
          this.pageLimt = parseInt(limit)
        }
        this.getCouponList(this.currentPage, this.pageLimt)
      }
    },
    isShowAddForm: {
      handler(val) {
        if (!val) {
          //清空表单
          this.form = this.getform()
          this.selectSkuList = []
          this.startAndEndTime = []
          this.CouponType = ''
        }
      }
    }
  },
  methods: {
    delSelect() {
      const { delCouponIdList } = this
      if (delCouponIdList.length == 0) {
        return
      }
      // 对话确认
      this.$confirm('', '确认删除吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(async () => {
          const res = await this.$API.coupon.delCouponBatch(delCouponIdList)
          if (res.ok) {
            await this.getCouponList()
            this.delCouponIdList = []
            this.$message({ type: 'success', message: '删除成功' })
          } else {
            
            this.$message({
              type: 'error',
              message: res.message + ' ' + (res.data || '')
            })
          }
        })
        .catch(() => {})
    },
    selectChange(list) {
      this.delCouponIdList = list.map((item) => item.id)
    },
    //删除优惠券
    async delCouponInfo(id) {
      const res = await this.$API.coupon.delCouponInfo(id)
      if (res.ok) {
        await this.getCouponList()
        this.$message({ type: 'success', message: '删除成功' })
      } else {
        this.$message({
          type: 'error',
          message: res.message + ' ' + (res.data || '')
        })
      }
    },
    clickSelectSku() {
      //发送已经选择的skuid
      var loading = this.$loading({
        target: '.add-edit-coupon',
        text: '正在加载中...'
      })
      this.$Bus.$emit('initSkuIdList', this.form.skuIdList, () => {
        this.isShowSelectSKU = true
        loading.close()
      })
      // this.isShowSelectSKU = true
    },
    //点击修改优惠券
    eidtCouponInfo(row) {
      const { form } = this
      // form.couponName = row.couponName
      // form.rangeDesc = row.rangeDesc
      Object.assign(form, row)
      this.CouponType = row.couponTypeString
      this.startAndEndTime = [row.startTime, row.endTime]
      let loading = this.$loading({
        target: '.show-list',
        text: '正在加载中...'
      })
      this.$Bus.$emit('initSkuIdList', form.skuIdList, () => {
        this.isShowAddForm = true
        loading.close()
      })
      // this.isShowAddForm = true
    },
    //添加,修改优惠券
    addCouponInfo() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const res = await this.$API.coupon.addCouponInfo(this.form)
          if (res.ok) {
            this.$message({
              type: 'success',
              message: this.form.id ? '修改成功' : '添加成功'
            })
            this.getCouponList()
            this.isShowAddForm = false
          } else {
            this.$message({
              type: 'error',
              message: res.message + ':' + (res.data || '')
            })
          }
        }
      })
    },
    //获取选中sku
    getSelectList(list) {
      this.selectSkuList = list
      this.form.skuIdList = list.map((item) => item.id)
    },
    //
    selectStartAndEndTime(value) {
      //2022-11-19T07:33:01.706Z
      //"2022-06-03 00:00:00"
      this.form.startTime = value[0]
      this.form.endTime = value[1]
    },
    selectCouponType(value) {
      this.form.couponType = value.split('|')[0]
      this.form.couponTypeString = value.split('|')[1]
    },
    //生成空的优惠券数据
    getform() {
      return {
        activityId: undefined,
        benefitAmount: 0,
        benefitDiscount: 0,
        conditionAmount: 0,
        conditionNum: 0,
        couponName: '',
        couponStatus: 'NOT_USED',
        couponType: 'FULL_REDUCTION',
        couponTypeString: '',
        createTime: '',
        endTime: '',
        expireTime: '',
        id: undefined,
        isChecked: 0,
        isGet: 0,
        isSelect: 0,
        limitNum: 0,
        operateTime: '',
        rangeDesc: '',
        rangeId: undefined,
        rangeType: 'SPU',
        rangeTypeString: '',
        reduceAmount: 0,
        skuIdList: [],
        startTime: '',
        takenCount: 0
      }
    },
    //过滤优惠券类型
    filterCouponType(value, row) {
      return row.couponType === value
    },
    //搜索优惠券
    async searchCoupon() {
      const { searchKeyword } = this
      if (searchKeyword) {
        const res = await this.$API.coupon.searchCoupon(searchKeyword)
        if (res.ok) {
          this.couponList = res.data
          //隐藏分页器
          this.showPagination = false
        } else {
          this.$message({
            type: 'error',
            message: res.message + ':' + (res.data || '')
          })
        }
      } else {
        this.getCouponList()
        //显示分页器
        this.showPagination = true
      }
    },
    //每页数量改变
    pageLimtChange(value) {
      this.pageLimt = parseInt(value)
      this.pageChange(undefined, value)
    },
    //页数改变,路由跳转
    pageChange(page = this.curPage, limit = this.pageLimt) {
      this.$router.push(
        {
          name: 'CouponList',
          query: {
            page,
            limit
          }
        },
        () => {},
        () => {}
      )
    },
    //
    async getCouponList(page = this.curPage, limit = this.pageLimt) {
      const res = await this.$API.coupon.getCouponList(page, limit)
      if (res.ok) {
        const { data } = res
        this.total = data.total
        this.couponList = data.records
      }
    }
  },
  created() {}
}
</script>

<style>
.addcoupon-card {
  border-radius: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.width20 {
  width: 60%;
}
.width30 {
  width: 70%;
}
.width40 {
  width: 90%;
}
.demo-table-expand {
  font-size: 0;
  border-radius: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}
.demo-table-expand label {
  color: #6495db;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
}

.pagination .computer {
  display: none !important;
}

@media screen and (min-width: 768px) {
  .width20 {
    width: 20%;
  }

  .width30 {
    width: 30%;
  }

  .width40 {
    width: 40%;
  }

  .pagination .computer {
    display: block !important;
  }

  .pagination .phone {
    display: none !important;
  }
}
</style>
